package cn.spream.jstudy.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by sjx on 2015/11/6.
 */
public class NettyServer {

    private final ServerBootstrap serverBootstrap = new ServerBootstrap();
    private int port;
    private ChannelHandler channelHandler;

    public NettyServer(int port, ChannelHandler channelHandler) {
        this.port = port;
        this.channelHandler = channelHandler;
    }

    public void start() throws InterruptedException {
        final EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup();
        final EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
        try {
            serverBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
            serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ChannelHandler[]{new NettyEncoder(), new NettyDecoder(), channelHandler});
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerEventLoopGroup.shutdownGracefully();
            bossEventLoopGroup.shutdownGracefully();
        }
    }

}
